/*
*  此文件主要处理用户更改上面图片或者描述图片
*       对其进行删除数据库数据 并且 删除图片
*       将最新的图片路径保存到数据库中
* */
const fs = require('fs') // 引入fs核心模块
const path = require('path')
exports.upDataUrlAndDelFile = function(obj) {
    // delUrl 为需要在数据库中删除的路径
    // dataUrl 为数据库已存的路径
    // dataName 为数据存的文件名，用于删除文件
    let code = [];
    let fileName = []
    if (obj.delUrl) {
        if (obj.delUrl instanceof Array) {
            for (let i in obj.delUrl) {
               let num = -1;
                obj.dataUrl.filter((item, index)=> {
                    if (item.url === obj.delUrl[i]) {
                        num = index
                    }
                })
                if (num != -1) {
                    fileName.push(obj.dataName[num]);
                    code.push(num);
                }
            }
        } else {
            let num = -1;
            obj.dataUrl.filter((item, index)=> {
                if (item.url ===obj.delUrl) {
                    num = index
                }
            })
            if (num != -1) {
                fileName.push(obj.dataName[num]);
                code.push(num);
            }
        }

    } else {
        return
    }
    code = code.sort();
    for (let i = code.length -1; i >= 0; i--) {
        obj.dataUrl.splice(i, 1);
    }
    for (let i = code.length -1; i >= 0; i--) {
        obj.dataName.splice(i, 1);
    }
    fileName.forEach(item=> {
        fs.unlink(path.join(process.cwd(),'public', 'img', obj.path, item), err=>{
            if (err) {
                console.log(err.message)
            }
        })
    })

}
exports.getNewUrlAndFileName = function (arr, data, identification) {
    let url = [];
    let fileName = [];
    if (identification === 'goods') {
        arr.forEach(item=> {
            url.push(`http://localhost:3000/public/img/goods/${item.filename}`);
            fileName.push(item.filename)
        })
        url.forEach(item=> {
            data.goodsImg.push({url: item})
        })
        data.goodsFilename.push(...fileName)
    } else if (identification === 'goodsDesc') {
        arr.forEach(item=> {
            url.push(`http://localhost:3000/public/img/goodsdesc/${item.filename}`);
            fileName.push(item.filename)
        })
        url.forEach(item=> {
            data.desImg.push({url: item})
        })
        data.descFilename.push(...fileName)
    }

}
exports.appendParams = function (arr, data, title) {
    let url = [];
    let fileName = [];
    arr.forEach((item, index)=> {
       if (title instanceof Array) {
           data.params.push({
               title: title[index],
               url: `http://localhost:3000/public/img/goodsparams/${item.filename}`
           })
       } else {
           data.params.push({
               title: title,
               url: `http://localhost:3000/public/img/goodsparams/${item.filename}`
           })
       }
        data.paramsFilename.push(item.filename)
    })
}